package com.skyk.util.upload;

import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.skyk.config.exception.BaseException;
import com.skyk.pojo.entity.User;
import com.skyk.pojo.vo.UserExportVO;
import com.skyk.service.impl.UserServiceImpl;
import org.springframework.beans.BeanUtils;

import java.util.LinkedList;
import java.util.List;

public class UserListener implements ReadListener<UserExportVO> {

    // 读取下标
    int i = 1;

    // 临时存储
    List<User> list = new LinkedList<>();

    private final UserServiceImpl userService;

    public UserListener(UserServiceImpl userService) {
        this.userService = userService;
    }

    /**
     * 这个每一条数据解析都会来调用
     */
    @Override
    public void invoke(UserExportVO userExportVO, AnalysisContext analysisContext) {
        checkData(userExportVO);
        User user = new User();
        user.setState(userExportVO.getState().equals("启用"));
        BeanUtils.copyProperties(userExportVO, user);
        user.setPassword("123456");
        list.add(user);
        i++;
    }

    /**
     * 所有数据解析完成了 都会来调用
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        userService.saveBatch(list);
        list.clear();
    }

    private void checkData(UserExportVO userExportVO) {
        if (StrUtil.isBlank(userExportVO.getGender()) || !StrUtil.equalsAny(userExportVO.getGender(), "男", "女")) {
            throw new BaseException(StrUtil.format("第{}行性别有误)", i));
        }
        if (StrUtil.isBlank(userExportVO.getPhoneNumber()) || PhoneUtil.isPhone(userExportVO.getPhoneNumber())) {
            throw new BaseException(StrUtil.format("第{}行手机号有误)", i));
        }
        if (StrUtil.isBlank(userExportVO.getUsername())) {
            throw new BaseException(StrUtil.format("第{}行用户名有误)", i));
        }
        if (StrUtil.isBlank(userExportVO.getState()) || !StrUtil.equalsAny(userExportVO.getState(), "启用", "禁用")) {
            throw new BaseException(StrUtil.format("第{}行状态有误)", i));
        }
    }

}
